<template>
  <div class="about">
    <el-card>
      <h1>{{ id ? "编辑" : "新建" }}文章</h1>
      <el-form label-width="120px" @submit.native.prevent="save">
        <el-form-item label="所属分类">
          <el-select v-model="model.categories" multiple>
            <el-option
              v-for="item in categories"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="model.title"></el-input>
        </el-form-item>
        <el-form-item label="详情">
          <vue-editor
            v-model="model.body"
            useCustomImageHandler
            @image-added="handleImageAdded"
          ></vue-editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="submit">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { VueEditor } from "vue2-editor"; //一个易于使用但功能强大且可定制的富文本编辑器，由Quill.js和Vue.js提供支持

export default {
  props: {
    id: {},
  },
  components: {
    VueEditor,
  },
  data() {
    return {
      model: {},
      categories: [],
    };
  },
  methods: {
    async save() {
      let res;
      if (this.id) {
        res = await this.$http.put(`rest/articles/${this.id}`, this.model);
      } else {
        res = await this.$http.post("rest/articles", this.model); //eslint-disable-line no-unused-vars
      }
      this.$router.push("/articles/list");
      this.$message({
        type: "success",
        message: "保存成功",
      });
    },
    async fetch() {
      const res = await this.$http.get(`rest/articles/${this.id}`);
      this.model = res.data;
    },
    async fetchCategories() {
      const res = await this.$http.get("rest/categories");
      this.categories = res.data;
    },
    // 富文本编辑器当然是可以上传图片的，但是上传的图片是以base64编码直接当作文本一起传到后台接口的
    // 图片的大小会影响接口上传速度，如果我们上传多张高达十几兆大小的图片，很可能对接口传值的负载过大，引起崩溃
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      // An example of using FormData
      // NOTE: Your key could be different such as:
      // formData.append('file', file)

      var formData = new FormData(); // 提交表单数据 FormData对象可以直接通过send传递
      formData.append("file", file); // 追加表单项 formData.append('key','value'
      const res = await this.$http.post("upload", formData);
      Editor.insertEmbed(cursorLocation, "image", res.data.url); //// 用vue-editor包自带的插入方法:在光标所在位置,插入一张图片,图片的地址是res.data.url
      resetUploader(); // // 刷新(重置)编辑器
    },
  },

  created() {
    this.fetchCategories();
    this.id && this.fetch();
  },
};
</script>

<style>
</style>